﻿using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Linq;
using System.Text;
using System.Data;
using Microsoft.SharePoint;
using TemplateLibraryConnector.Utility;

namespace TemplateLibraryConnector.Data
{
    public class AllTemplates : BaseTemplates
    {

        public AllTemplates(TemplateLibrarySettings settings) : base(settings)
        {
        }

        public override DataTable GetItems(Guid viewId)        
        {
            var doclibAbsoluteUrl = Settings.GetTemplateHubAddress(string.Empty);
            var listId = new Guid(Settings.TemplateListIds);

            using (var site = new SPSite(doclibAbsoluteUrl))
            {
                var relativeSubWebUrl = doclibAbsoluteUrl.ToLower().Replace(site.Url.ToLower(), "");
                using (var web = site.OpenWeb(relativeSubWebUrl))
                {
                    var docLib = web.Lists[listId] as SPDocumentLibrary;
                    var view = docLib.GetView(viewId);
                    var viewFields = view.ViewFields;

                    TemplateLibraryDataUtility.AddRequiredFieldsToView(viewFields, docLib.Fields);
                    
                    return GetDataTable(docLib.GetItems(view));
                }
            }
        }

        public override DataTable Items()
        {
            var doclibAbsoluteUrl = Settings.GetTemplateHubAddress(string.Empty);
            var listId = new Guid(Settings.TemplateListIds);

            using (var site = new SPSite(doclibAbsoluteUrl))
            {
                var relativeSubWebUrl = doclibAbsoluteUrl.ToLower().Replace(site.Url.ToLower(), "");
                using (var web = site.OpenWeb(relativeSubWebUrl))
                {
                    var docLib = web.Lists[listId] as SPDocumentLibrary;
                    return GetDataTable(docLib.GetItems());
                }
            }   
        }


        private DataTable GetDataTable(SPListItemCollection itemCollection)
        {
            var dt = new DataTable();
            const string itemLinkUrl = "GOTO_ITEM_URL";

            var fieldsNameCollection = itemCollection.QueryFieldNames;
            for (var i = 0; i < fieldsNameCollection.Count; i++)
            {
                if (fieldsNameCollection[i].StartsWith("ows_"))
                    fieldsNameCollection[i] = fieldsNameCollection[i].Remove(0, 4);
                dt.Columns.Add(new DataColumn(fieldsNameCollection[i]));
            }

            dt.Columns.Add(new DataColumn(itemLinkUrl));
            
            foreach (SPListItem item in itemCollection)
            {
                if (item.HasPublishedVersion)
                {
                    var dr = dt.NewRow();
                    foreach (var field in from string t in fieldsNameCollection select item.Fields.GetFieldByInternalName(t))
                    {
                        if (field == null) throw new Exception();
                        if (field is SPFieldLookup)
                        {
                            var lf = field as SPFieldLookup;
                            dr[field.InternalName] = lf.GetFieldValueAsText(item[field.InternalName]);
                        }
                        else if (field is SPFieldUrl)
                        {
                            var lf = field as SPFieldUrl;
                            dr[field.InternalName] = lf.GetFieldValueAsHtml(item[field.InternalName]);
                        }
                        else dr[field.InternalName] = item[field.InternalName];
                    }
                    dt.Rows.Add(dr);
                }
            }
            return dt;
        }

        private static string EnsureBasicFields(string viewFields)
        {
            const string title = "Title";
            const string author = "Author";
            const string editor = "Editor";
            const string created = "Created";
            const string modified = "Modified";
            const string itemEncodedAbsUrl = "EncodedAbsUrl";
            var basicFields = new string[] {title, author, editor, created, modified, itemEncodedAbsUrl};
            foreach (var str in basicFields.Where(str => !viewFields.Contains(String.Format("", str))))
            {
                viewFields = String.Concat(viewFields, String.Format("", str));
            }
            return viewFields;
        } 
    }
}
